﻿/*------------------------------------------------------------------------
 *功能描述：分页控件
 <Page:Pagination ID="pc" runat="server" CPageQueryName="page" CssClass="page page2"
     CurrentPageClassName="current" DisplayGoPage="True" DisplayGoPageButton="True"
     DisplayMessage="True" DisplayMessageClassName="mess" DisplayNextButton="True" DisplayPreviousButton="True" FirstText="第一页"
     GoPageButtonClass="ybut" GoPageText="跳转到" LastText="最后页" NextPageText="下一页" NoData="对不起!没有任何相关数据"
     PreviousPageText="上一页" />
-------------------------------------------------------------------------*/
using System;
using System.Web;
using System.Web.UI;
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;

namespace Aj.Core.Control
{
    /// <summary>
    /// 基于URL查询字符创的分页控件，必须提供PageStructure类实例用于构建控件
    /// </summary>
    [ToolboxData("<{0}:Pagination runat=\"server\"></{0}:Pagination")]
    [Designer(typeof(PageDesign))]
    public class Pagination : WebControl
    {
        #region 获取控件主体HTML
        internal string GetContentHTML(bool design)
        {
            //如果现在是设计运行时
            if (design)
            {
                this.pagestructure = new PageStructure();
                isDesignMode = true;
            }
            if (this.pagestructure == null)
            {
                return "";
            }
            StringBuilder writer = new StringBuilder();
            //计算出了页码的个数（会分几页）
            int PageCount = pagestructure.PageCount = (int)Math.Ceiling((double)PageStruct.Counts / PageStruct.PageSize);
            //计算页码会分几次显示
            int PageDisplayDegree = (int)Math.Ceiling((double)PageCount / DisplayPage);

            //如果分页数小于1那么不创建任何项
            if (PageCount < 1)
            {
                return this.NoData;

            }
            //如果当前页大于总页数那么取总页数最大值
            if (PageStruct.CurrPage > PageCount)
            {
                PageStruct.CurrPage = PageCount;
            }
            //创建开始标签
            writer.AppendFormat("<{1}{0}>", this.CssClass == "" ? "" : " class=\"" + this.CssClass + "\"", this.PanelTag);

            if (PageCount > 2 && DisplayFirstPageButton && !(DisplayPage < 1))
            {
                //创建第一页按钮
                string thefirst = "";
                if (PageStruct.CurrPage == 1)
                {
                    thefirst = FirstImage == "" || FirstImage == null
                    ? string.Format("<span{0}>{1}</span>", NavigationAbateClassName == null || NavigationAbateClassName == ""
                    ? ""
                    : string.Format(" class=\"{0}\"", NavigationAbateClassName), HttpUtility.HtmlEncode(this.FirstText))
                    : string.Format("<img alt=\"第一页\" src=\"{0}\"{1} />", this.FirstImage, NavigationAbateClassName == null
                    || NavigationAbateClassName == "" ? "" : string.Format(" class=\"{0}\"", NavigationAbateClassName));
                    writer.Append(thefirst);
                }
                else
                {
                    thefirst = FirstImage == "" || FirstImage == null
                    ? string.Format("{0}", HttpUtility.HtmlEncode(this.FirstText))
                    : string.Format("<img alt=\"第一页\" src=\"{0}\" />", this.FirstImage);
                    writer.Append(createPageButton(thefirst, FirstAndLastClassName == null ? "" : FirstAndLastClassName, "1"));
                }
            }
            //创建上一页按钮
            if (PageCount > 1 && DisplayPreviousButton)
            {
                string thePre = "";
                if (PageStruct.CurrPage == 1)
                {
                    thePre = string.IsNullOrEmpty(PreviousPageImg) ? string.Format("<span{0}>{1}</span>", string.IsNullOrEmpty(NoDataNPButtonClass) ? "" : string.Format(" class=\"{0}\"", NoDataNPButtonClass), PreviousPageText)
                         : string.Format("<img alt=\"上一页\" src=\"{0}\"{1} />", this.PreviousPageImg, string.IsNullOrEmpty(NoDataNPButtonClass) ? "" : string.Format(" class=\"{0}\"", NoDataNPButtonClass));
                    writer.Append(thePre);
                }
                else
                {
                    thePre = string.IsNullOrEmpty(PreviousPageImg)
                  ? string.Format("{0}", HttpUtility.HtmlEncode(this.PreviousPageText))
                  : string.Format("<img alt=\"上一页\" src=\"{0}\" />", this.PreviousPageImg);
                    writer.Append(createPageButton(thePre, NPButtonClass, PageStruct.CurrPage - 1));
                }
            }
            //如果要将所有的页码全部显示完
            if (DisplayPage < 1)
            {
                render(writer, 1, PageCount, PageStruct.CurrPage);
            }
            //当所有的页码能够一次显示完成的时候
            else if (PageCount < DisplayPage || PageCount == DisplayPage)
            {
                render(writer, 1, PageCount, PageStruct.CurrPage);
            }
            //如果当前显示的页码数，位于页码页的第一页，那么需要在最后一页页码按钮后面加入“更多页码”按钮
            else if (PageStruct.CurrPage <= DisplayPage && PageCount > DisplayPage)
            {
                render(writer, 1, DisplayPage, PageStruct.CurrPage);
                writer.Append(createMoreButton((DisplayPage + 1).ToString()));
                // writer.Append(createPageButton(MoreImage == "" ? MoreText : MoreImage, MorePageClassName, (DisplayPage + 1).ToString()));
            }
            //如果当前显示的页码数，位于页码页的最后，那么需要在最前一页页码按钮前面加入“更多页码”按钮
            else if (PageStruct.CurrPage <= PageCount && PageStruct.CurrPage > ((PageDisplayDegree - 1) * DisplayPage))
            {
                // writer.Append(createPageButton(MoreImage == "" ? MoreText : MoreImage, MorePageClassName, (DisplayPage * PageDisplayDegree).ToString()));
                writer.Append(createMoreButton((DisplayPage * (PageDisplayDegree - 1)).ToString()));
                render(writer, (DisplayPage * (PageDisplayDegree - 1)) + 1, PageCount, PageStruct.CurrPage);

            }
            //如果以上都不满足说明当前页码位于页码页中部，即需要在当前显示的页码的最前和最后页码按钮分别加“更多页码”按钮
            else
            {
                int end = PageStruct.CurrPage % DisplayPage == 0 ? PageStruct.CurrPage : PageStruct.CurrPage + (DisplayPage - (PageStruct.CurrPage % DisplayPage));
                int start = end - DisplayPage + 1;
                writer.Append(createMoreButton((start - 1).ToString()));
                render(writer, start, end, PageStruct.CurrPage);
                writer.Append(createMoreButton((end + 1).ToString()));

            }
            //创建下一页按钮
            if (PageCount > 1 && DisplayNextButton)
            {
                string thePre = "";
                if (PageStruct.CurrPage == PageCount)
                {
                    thePre = string.IsNullOrEmpty(NextPageImg) ? string.Format("<span{0}>{1}</span>", string.IsNullOrEmpty(NoDataNPButtonClass) ? "" : string.Format(" class=\"{0}\"", NoDataNPButtonClass), NextPageText)
                         : string.Format("<img alt=\"下一页\" src=\"{0}\"{1} />", this.NextPageImg, string.IsNullOrEmpty(NoDataNPButtonClass) ? "" : string.Format(" class=\"{0}\"", NoDataNPButtonClass));
                    writer.Append(thePre);
                }
                else
                {
                    thePre = string.IsNullOrEmpty(NextPageImg)
                  ? string.Format("{0}", HttpUtility.HtmlEncode(this.NextPageText))
                  : string.Format("<img alt=\"下一页\" src=\"{0}\" />", this.NextPageImg);
                    writer.Append(createPageButton(thePre, NPButtonClass, PageStruct.CurrPage + 1));
                }
            }
            //创建最后一页按钮
            if (PageCount > 2 && DisplayLastPageButton && !(DisplayPage < 1))
            {
                string thelast = "";

                if (PageStruct.CurrPage == PageCount)
                {
                    thelast = LastImage == "" || LastImage == null
                    ? string.Format("<span{0}>{1}</span>", NavigationAbateClassName == null || NavigationAbateClassName == ""
                    ? ""
                    : string.Format(" class=\"{0}\"", NavigationAbateClassName), HttpUtility.HtmlEncode(this.LastText))
                    : string.Format("<img alt=\"最后页\" src=\"{0}\"{1} />", this.LastImage, NavigationAbateClassName == null
                    || NavigationAbateClassName == "" ? "" : string.Format(" class=\"{0}\"", NavigationAbateClassName));
                    writer.Append(thelast);
                }
                else
                {
                    thelast = LastImage == "" || LastImage == null
                    ? string.Format("{0}", HttpUtility.HtmlEncode(this.LastText))
                    : string.Format("<img alt=\"最后页\" src=\"{0}\"/>", this.LastImage);

                    writer.Append(createPageButton(thelast, FirstAndLastClassName == null ? "" : FirstAndLastClassName, PageCount.ToString()));
                }
            }
            if (DisplayMessage)
            {
                writer.AppendFormat("<span{4}>" + PageMessageFormat + "</span>", pagestructure.Counts, pagestructure.PageSize, pagestructure.PageCount, pagestructure.CurrPage, (string.IsNullOrEmpty(DisplayMessageClassName) ? "" : " class=\"" + DisplayMessageClassName + "\""));
            }
            if (DisplayGoPage)
            {
                if (isDesignMode)
                {
                    writer.Append(string.Format(DisplayGoPageButton ? goPageHtml + goButtonHtml : goPageHtml, string.IsNullOrEmpty(GoPageTextClass) ? "" : string.Format("class=\"{0}\"", GoPageTextClass), "#", "#", GoPageButtonText, string.IsNullOrEmpty(GoPageButtonClass) ? "" : string.Format("class=\"{0}\"", GoPageButtonClass), 5, GoPageText));
                }
                else
                {
                    if (PageCount > 1)
                    {

                        writer.Append(string.Format(DisplayGoPageButton ? goPageHtml + goButtonHtml : goPageHtml, string.IsNullOrEmpty(GoPageTextClass) ? "" : string.Format("class=\"{0}\"", GoPageTextClass), linkUrl.ToString(), "{ThisPagePlaceholder}", GoPageButtonText, string.IsNullOrEmpty(GoPageButtonClass) ? "" : string.Format("class=\"{0}\"", GoPageButtonClass), PageCount + 1, GoPageText));
                    }
                }

            }
            writer.AppendFormat("</{0}>", this.PanelTag);

            return writer.ToString();
        }
        #endregion

        public override void RenderControl(HtmlTextWriter writer)
        {

            #region 恢复视图状态

            if (ViewState["PageControlState_" + this.ID] != null)
            {
                this.PageStruct = (PageStructure)ViewState["PageControlState_" + this.ID];
            }
            if (ViewState["PageControlState_" + this.ID + "_DisplayMessageClassName"] != null)
            {
                this.DisplayMessageClassName = (ViewState["PageControlState_" + this.ID + "_DisplayMessageClassName"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_DisplayMessage"] != null)
            {
                this.DisplayMessage = (bool)(ViewState["PageControlState_" + this.ID + "_DisplayMessage"]);
            }
            if (ViewState["PageControlState_" + this.ID + "_CPageQueryName"] != null)
            {
                this.CPageQueryName = (ViewState["PageControlState_" + this.ID + "_CPageQueryName"]).ToString();
            }

            if (ViewState["PageControlState_" + this.ID + "_DisplayPage"] != null)
            {
                this.DisplayPage = Convert.ToInt32(ViewState["PageControlState_" + this.ID + "_DisplayPage"]);
            }

            if (ViewState["PageControlState_" + this.ID + "_CurrentPageClassName"] != null)
            {
                this.CurrentPageClassName = (ViewState["PageControlState_" + this.ID + "_CurrentPageClassName"]).ToString();
            }

            if (ViewState["PageControlState_" + this.ID + "_PageNumberClassName"] != null)
            {
                this.PageNumberClassName = (ViewState["PageControlState_" + this.ID + "_PageNumberClassName"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_FirstAndLastClassName"] != null)
            {
                this.FirstAndLastClassName = (ViewState["PageControlState_" + this.ID + "_FirstAndLastClassName"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_MorePageClassName"] != null)
            {
                this.MorePageClassName = (ViewState["PageControlState_" + this.ID + "_MorePageClassName"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_NavigationAbateClassName"] != null)
            {
                this.NavigationAbateClassName = (ViewState["PageControlState_" + this.ID + "_NavigationAbateClassName"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_FirstImage"] != null)
            {
                this.FirstImage = (ViewState["PageControlState_" + this.ID + "_FirstImage"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_LastImage"] != null)
            {
                this.LastImage = (ViewState["PageControlState_" + this.ID + "_LastImage"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_FirstText"] != null)
            {
                this.FirstText = (ViewState["PageControlState_" + this.ID + "_FirstText"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_LastText"] != null)
            {
                this.LastText = (ViewState["PageControlState_" + this.ID + "_LastText"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_MoreText"] != null)
            {
                this.MoreText = (ViewState["PageControlState_" + this.ID + "_MoreText"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_PanelTag"] != null)
            {
                this.PanelTag = (ViewState["PageControlState_" + this.ID + "_PanelTag"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_MoreImage"] != null)
            {
                this.MoreImage = (ViewState["PageControlState_" + this.ID + "_MoreImage"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_DisplayFirstPageButton"] != null)
            {
                this.DisplayFirstPageButton = (bool)ViewState["PageControlState_" + this.ID + "_DisplayFirstPageButton"];
            }
            if (ViewState["PageControlState_" + this.ID + "_DisplayLastPageButton"] != null)
            {
                this.DisplayLastPageButton = (bool)ViewState["PageControlState_" + this.ID + "_DisplayLastPageButton"];
            }
            if (ViewState["PageControlState_" + this.ID + "_PageMessageFormat"] != null)
            {
                this.PageMessageFormat = (ViewState["PageControlState_" + this.ID + "_PageMessageFormat"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_NoData"] != null)
            {
                this.NoData = (ViewState["PageControlState_" + this.ID + "_NoData"]).ToString();//
            }
            if (ViewState["PageControlState_" + this.ID + "_DisplayPreviousButton"] != null)
            {
                this.DisplayPreviousButton = (bool)ViewState["PageControlState_" + this.ID + "_DisplayPreviousButton"];
            }
            if (ViewState["PageControlState_" + this.ID + "_DisplayNextButton"] != null)
            {
                this.DisplayNextButton = (bool)ViewState["PageControlState_" + this.ID + "_DisplayNextButton"];
            }
            if (ViewState["PageControlState_" + this.ID + "_PreviousPageText"] != null)
            {
                this.PreviousPageText = (ViewState["PageControlState_" + this.ID + "_PreviousPageText"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_NextPageText"] != null)
            {
                this.NextPageText = (ViewState["PageControlState_" + this.ID + "_NextPageText"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_NextPageImg"] != null)
            {
                this.NextPageImg = (ViewState["PageControlState_" + this.ID + "_NextPageImg"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_PreviousPageImg"] != null)
            {
                this.PreviousPageImg = (ViewState["PageControlState_" + this.ID + "_PreviousPageImg"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_NPButtonClass"] != null)
            {
                this.NPButtonClass = (ViewState["PageControlState_" + this.ID + "_NPButtonClass"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_NoDataNPButtonClass"] != null)
            {
                this.NoDataNPButtonClass = (ViewState["PageControlState_" + this.ID + "_NoDataNPButtonClass"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_Target"] != null)
            {
                this.Target = (ViewState["PageControlState_" + this.ID + "_Target"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_TargetUrlFormat"] != null)
            {
                this.TargetUrlFormat = (ViewState["PageControlState_" + this.ID + "_TargetUrlFormat"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_DisplayGoPage"] != null)
            {
                this.DisplayGoPage = (bool)ViewState["PageControlState_" + this.ID + "_DisplayGoPage"];
            }
            if (ViewState["PageControlState_" + this.ID + "_GoPageButtonText"] != null)
            {
                this.GoPageButtonText = (ViewState["PageControlState_" + this.ID + "_GoPageButtonText"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_GoPageText"] != null)
            {
                this.GoPageText = (ViewState["PageControlState_" + this.ID + "_GoPageText"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_GoPageTextClass"] != null)
            {
                this.GoPageTextClass = (ViewState["PageControlState_" + this.ID + "_GoPageTextClass"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_GoPageButtonClass"] != null)
            {
                this.GoPageButtonClass = (ViewState["PageControlState_" + this.ID + "_GoPageButtonClass"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_PageTextFormat"] != null)
            {
                this.PageTextFormat = (ViewState["PageControlState_" + this.ID + "_PageTextFormat"]).ToString();
            }
            if (ViewState["PageControlState_" + this.ID + "_CurrentPageTextFormat"] != null)
            {
                this.CurrentPageTextFormat = (ViewState["PageControlState_" + this.ID + "_CurrentPageTextFormat"]).ToString();
            }
            #endregion
            writer.Write(GetContentHTML(false));
        }

        #region 方法
        public string GetDesignHtml()
        {
            return GetContentHTML(true);
        }
        /// <summary>
        /// 创建更多页码按钮
        /// </summary>
        /// <param name="queryvalue"></param>
        /// <returns></returns>
        private string createMoreButton(string queryvalue)
        {
            return createPageButton(MoreImage == null || MoreImage == "" ? HttpUtility.HtmlEncode(MoreText) : string.Format("<img alt=\"更多\" src=\"{0}\" />", MoreImage), MorePageClassName, queryvalue);
        }
        /// <summary>
        /// 创建连续的页码
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="current"></param>
        private void render(StringBuilder writer, int start, int end, int current)
        {
            for (int i = start; i <= end; i++)
            {
                if (i == current)
                {
                    writer.Append(string.Format(string.IsNullOrEmpty(CurrentPageClassName) ? "<span>{0}</span>\n" : "<span{1}>{0}</span>", string.Format(CurrentPageTextFormat, i), " class=\"" + CurrentPageClassName + "\""));
                    continue;
                }
                writer.Append(createPageButton(string.Format(PageTextFormat, i), i.ToString()));
            }
        }
        /// <summary>
        /// 返回一个页码按钮连接的html
        /// </summary>
        /// <param name="linktext">连接文本</param>
        /// <param name="quertvalue">连接页码参数值</param>
        /// <returns></returns>
        private string createPageButton(string linktext, object qv)
        {
            return string.Format("<a href=\"{0}\" {1}{3}><span>{2}</span></a>\n", getLinkUrl(qv), PageNumberClassName != null ? "class=\"" + PageNumberClassName + "\"" : "", linktext, string.IsNullOrEmpty(Target) ? "" : string.Format("target=\"{0}\"", Target));
        }
        /// <summary>
        /// 计算链接地址
        /// </summary>
        /// <param name="qv"></param>
        /// <returns></returns>
        private string getLinkUrl(object qv)
        {
            string quertvalue = qv.ToString();
            string OURL = "";
            linkUrl = new StringBuilder();
            if (!isDesignMode)
            {
                OURL = HttpContext.Current.Request.Url.AbsolutePath;
                //如果没有提供URL格式化字符串
                if (string.IsNullOrEmpty(TargetUrlFormat))
                {

                    if (HttpContext.Current.Request.QueryString[CPageQueryName] == null)
                    {
                        linkUrl.Append("?" + CPageQueryName + "={ThisPagePlaceholder}");
                    }
                    foreach (string i in HttpContext.Current.Request.QueryString.AllKeys)
                    {

                        if (!string.IsNullOrEmpty(i))
                        {
                            if (i.ToLower() == CPageQueryName.ToLower())
                            {
                                linkUrl.Append(linkUrl.Length > 0 ? "&" + CPageQueryName + "={ThisPagePlaceholder}" : "?" + CPageQueryName + "={ThisPagePlaceholder}");

                                continue;
                            }
                            linkUrl.Append(linkUrl.Length > 0 ? "&" + i + "=" + HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.QueryString[i].ToString()) : "?" + i + "=" + HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.QueryString[i].ToString()));

                        }
                    }


                    linkUrl.Insert(0, OURL);
                    return linkUrl.ToString().Replace("{ThisPagePlaceholder}", quertvalue);

                }
                else
                {

                    string pattern = @"(?<=\{)\w+(?=\})";
                    string pattern2 = @"\{\w+\}";
                    MatchCollection mcs = Regex.Matches(TargetUrlFormat, pattern);
                    ArrayList strs = new ArrayList(Regex.Split(TargetUrlFormat, pattern2));

                    if (mcs.Count > 0)
                    {
                        if (mcs[0].Index == 0)
                        {
                            for (int i = 0; i < mcs.Count; i++)
                            {

                                if (string.IsNullOrEmpty(strs[0].ToString()))
                                {
                                    strs.RemoveAt(0);
                                }
                                string queryName = mcs[i].Value;
                                if (queryName.ToLower() == "thispage")
                                {

                                    linkUrl.Append("{ThisPagePlaceholder}");
                                    linkUrl.Append(strs[i].ToString());
                                    continue;
                                }
                                if (HttpContext.Current.Request.QueryString[queryName] != null)
                                {
                                    linkUrl.Append(HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.QueryString[queryName].ToString()));
                                }
                                linkUrl.Append(strs[i].ToString());
                            }
                        }
                        else
                        {
                            int currentIndex = 0;
                            linkUrl.Append(strs[currentIndex].ToString());
                            for (int i = 0; i < mcs.Count; i++)
                            {
                                currentIndex += 1;
                                if (string.IsNullOrEmpty(strs[0].ToString()))
                                {
                                    strs.RemoveAt(0);
                                }

                                string queryName = mcs[i].Value;
                                if (queryName.ToLower() == "thispage")
                                {
                                    linkUrl.Append("{ThisPagePlaceholder}");
                                    linkUrl.Append(strs[currentIndex].ToString());
                                    continue;
                                }
                                if (HttpContext.Current.Request.QueryString[queryName] != null)
                                {
                                    linkUrl.Append(HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.QueryString[queryName].ToString()));
                                }
                                linkUrl.Append(strs[currentIndex].ToString());

                            }
                        }

                    }
                }


            }
            linkUrl = new StringBuilder(ResolveUrl(linkUrl.ToString()));

            return ResolveUrl(linkUrl.ToString().Replace("{ThisPagePlaceholder}", quertvalue));
        }
        /// <summary>
        /// 返回一个页码按钮连接的html,可提供样式表类名
        /// </summary>
        /// <param name="linktext">连接文本</param>
        /// <param name="quertvalue">连接页码参数值</param>
        /// <returns></returns>
        private string createPageButton(string linktext, string classname, object qv)
        {
            return string.Format("<a href=\"{0}\" {1}{3}><span>{2}</span></a>\n", getLinkUrl(qv), !(string.IsNullOrEmpty(classname)) ? "class=\"" + classname + "\"" : "", linktext, string.IsNullOrEmpty(Target) ? "" : string.Format("target=\"{0}\"", Target));
        }
        #endregion

        #region 私有变量
        private bool isDesignMode = false;//当前是否是设计运行时
        private PageStructure pagestructure;
        private string pageMessageFormat;
        private string cpagequeryname;
        private int Displaypage;

        private StringBuilder linkUrl;
        private string currentPageClassName;
        private string pageNumberClassName;
        private string firstAndLastClassName;
        private string morePageClassName, displaymessageClassName, panelTag = "div";
        private string firstImage, lastImage, firstText, lastText, currentpagetextformat = "{0}", pagetextformat = "{0}", moreImage, moreText, navigationabateClassName;
        private string noData;
        private bool displayfirstpagebutton = true, displaylastpagebutton = true, displaymessage, displaypreviousbutton = true, displaynextbutton = true, displayGoPage, displayGoPageButton;
        private string nextPageText, previousPageText, nextPageImg, previousPageImg, npButtonClass, nodataNPButtonClass, target, targetUrlFormat, goPageTextClass, goPageButtonClass, goPageButtonText, goPageText;
        private static string goPageHtml
            = "<span>{6}</span><input type=\"text\" {0} onkeydown=\" var e=e||event;if(e.keyCode==13){{if(e.preventDefault){{e.preventDefault();}}else{{e.returnValue = false;}}}}\" onkeyup=\"var e=e||event;if(e.keyCode==13){{ var page=parseInt(this.value);if(page>0&&page<{5}){{window.location.href=('{1}').replace('{2}',page);return false;}}}}\"/>";
        private static string goButtonHtml
            = "<input type=\"button\" value=\"{3}\" {4} onclick=\"var page=parseInt(this.previousSibling.value);if(page>0&&page<{5}){{window.location.href=('{1}').replace('{2}',page)}}\"/>";
        #endregion

        #region 属性
        /// <summary>
        /// 用于构架此控件的数据源结构
        /// </summary>
        [Bindable(true), Category("数据"), Description("用于构架此控件的数据源结构")]
        public PageStructure PageStruct
        {
            get
            {
                return this.pagestructure;

            }
            set
            {
                this.pagestructure = value;
                ViewState["PageControlState_" + this.ID] = value;
            }
        }
        /// <summary>
        /// 链接的框架名
        /// </summary>
        [Bindable(true), Category("显示"), Description("链接的框架名")]
        public string Target
        {
            get
            {
                return this.target;
            }
            set
            {
                this.target = value;
                ViewState["PageControlState_" + this.ID + "_Target"] = value;
            }
        }
        /// <summary>
        /// 格式化链接目标URL的字符串,主要用于为生成静态页
        /// </summary>
        [Bindable(true), Category("显示"), Description("格式化链接目标URL的字符串,如当前页面为:\"ProductList.aspx?category=2&page=34\",此属性设置为:\"ProductList_{category}_{page}.htm\",那么本页上一页按钮将链接ProductList_2_33.htm,主要用于为生成静态页提供方便,但有个特殊参数{ThisPage},该参数表示页标识参数的值")]
        public string TargetUrlFormat
        {
            get
            {
                return this.targetUrlFormat;
            }
            set
            {
                this.targetUrlFormat = value;
                ViewState["PageControlState_" + this.ID + "_TargetUrlFormat"] = value;
            }
        }
        /// <summary>
        /// 页码文本的格式化字符串如[{0}]
        /// </summary>
        [Bindable(true), Category("显示"), Description("页码文本的格式化字符串如[{0}]")]
        public string PageTextFormat
        {
            get
            {
                return this.pagetextformat;
            }
            set
            {
                this.pagetextformat = value;
                ViewState["PageControlState_" + this.ID + "_PageTextFormat"] = value;
            }
        }
        /// <summary>
        /// 当前页码文本的格式化字符串如<b>{0}</b>
        /// </summary>
        [Bindable(true), Category("显示"), Description("当前页码文本的格式化字符串如<b>{0}</b>")]
        public string CurrentPageTextFormat
        {
            get
            {
                return this.currentpagetextformat;
            }
            set
            {
                this.currentpagetextformat = value;
                ViewState["PageControlState_" + this.ID + "_CurrentPageTextFormat"] = value;
            }
        }
        /// <summary>
        /// 上一页下一页按钮的class类名
        /// </summary>
        [Bindable(true), Category("显示"), Description("上一页下一页按钮的class类名")]
        public string NPButtonClass
        {
            get
            {
                return this.npButtonClass;
            }
            set
            {
                this.npButtonClass = value;
                ViewState["PageControlState_" + this.ID + "_NPButtonClass"] = value;
            }
        }
        /// <summary>
        /// 上一页下一页按钮失效时的class类名
        /// </summary>
        [Bindable(true), Category("显示"), Description("上一页下一页按钮失效时的class类名")]
        public string NoDataNPButtonClass
        {
            get
            {
                return this.nodataNPButtonClass;
            }
            set
            {
                this.nodataNPButtonClass = value;
                ViewState["PageControlState_" + this.ID + "_NoDataNPButtonClass"] = value;
            }
        }
        /// <summary>
        /// 上一页按钮的显示文本
        /// </summary>
        [Bindable(true), Category("显示"), Description("上一页按钮的显示文本")]
        public string PreviousPageText
        {
            get
            {
                return string.IsNullOrEmpty(this.previousPageText) ? "previous" : this.previousPageText;
            }
            set
            {
                this.previousPageText = value;
                ViewState["PageControlState_" + this.ID + "_PreviousPageText"] = value;
            }
        }
        /// <summary>
        /// 下一页按钮的显示文本
        /// </summary>
        [Bindable(true), Category("显示"), Description("下一页按钮的显示文本")]
        public string NextPageText
        {
            get
            {
                return string.IsNullOrEmpty(this.nextPageText) ? "next" : this.nextPageText;
            }
            set
            {
                this.nextPageText = value;
                ViewState["PageControlState_" + this.ID + "_NextPageText"] = value;
            }
        }
        /// <summary>
        /// 下一页按钮的图像
        /// </summary>
        [Bindable(true), Category("显示"), Description("下一页按钮的图像")]
        public string NextPageImg
        {
            get
            {
                return this.nextPageImg;
            }
            set
            {
                this.nextPageImg = value;
                ViewState["PageControlState_" + this.ID + "_NextPageImg"] = value;
            }
        }
        /// <summary>
        /// 上一页按钮的图像
        /// </summary>
        [Bindable(true), Category("显示"), Description("上一页按钮的图像")]
        public string PreviousPageImg
        {
            get
            {
                return this.previousPageImg;
            }
            set
            {
                this.previousPageImg = value;
                ViewState["PageControlState_" + this.ID + "_PreviousPageImg"] = value;
            }
        }
        /// <summary>
        /// 结构信息的样式表类名
        /// </summary>
        [Bindable(true), Category("显示"), Description("结构信息的样式表类名")]
        public string DisplayMessageClassName
        {
            get
            {
                return this.displaymessageClassName;
            }
            set
            {
                this.displaymessageClassName = value;
                ViewState["PageControlState_" + this.ID + "_DisplayMessageClassName"] = value;
            }
        }
        /// <summary>
        /// 控制分页控件容器的标签
        /// </summary>
        [Bindable(true), Category("显示"), Description("控制分页控件容器的标签")]
        public string PanelTag
        {
            get
            {
                return this.panelTag;
            }
            set
            {
                this.panelTag = value;
                ViewState["PageControlState_" + this.ID + "_PanelTag"] = value;
            }
        }
        /// <summary>
        /// 当没有任何数据的时候显示的文本
        /// </summary>
        [Bindable(true), Category("显示"), Description("当没有任何数据的时候显示的文本")]
        public string NoData
        {
            get
            {
                return this.noData;
            }
            set
            {
                this.noData = value;
                ViewState["PageControlState_" + this.ID + "_NoData"] = value;
            }
        }
        /// <summary>
        /// 页面跳转文本框的样式表类名
        /// </summary>
        [Bindable(true), Category("显示"), Description("页面跳转文本框的样式表类名")]
        public string GoPageTextClass
        {
            get
            {
                return this.goPageTextClass;
            }
            set
            {
                this.goPageTextClass = value;
                ViewState["PageControlState_" + this.ID + "_GoPageTextClass"] = value;
            }
        }
        /// <summary>
        /// 页面跳转按钮的样式表类名
        /// </summary>
        [Bindable(true), Category("显示"), Description("页面跳转按钮的样式表类名")]
        public string GoPageButtonClass
        {
            get
            {
                return this.goPageButtonClass;
            }
            set
            {
                this.goPageButtonClass = value;
                ViewState["PageControlState_" + this.ID + "_GoPageButtonClass"] = value;
            }
        }
        /// <summary>
        /// 页面跳转按钮显示的文本
        /// </summary>
        [Bindable(true), Category("显示"), Description("页面跳转按钮显示的文本")]
        public string GoPageButtonText
        {
            get
            {
                return string.IsNullOrEmpty(this.goPageButtonText) ? "go" : this.goPageButtonText;
            }
            set
            {
                this.goPageButtonText = value;
                ViewState["PageControlState_" + this.ID + "_GoPageButtonText"] = value;
            }
        }
        /// <summary>
        /// 页面跳转区域前显示的文本
        /// </summary>
        [Bindable(true), Category("显示"), Description("页面跳转区域前显示的文本")]
        public string GoPageText
        {
            get
            {
                return this.goPageText;
            }
            set
            {
                this.goPageText = value;
                ViewState["PageControlState_" + this.ID + "_GoPageText"] = value;
            }
        }
        /// <summary>
        /// 是否显示控件结构信息
        /// </summary>
        [Bindable(true), Category("外观"), Description("是否显示控件结构信息,如:\n共有记录：{0}条，每页显示：{1}条，分{2}页显示，当前页：{3}")]
        public bool DisplayMessage
        {
            get
            {
                return displaymessage;
            }
            set
            {
                this.displaymessage = value;
                ViewState["PageControlState_" + this.ID + "_DisplayMessage"] = value;
            }
        }

        /// <summary>
        /// 是否显示页码跳转区域
        /// </summary>
        [Bindable(true), Category("外观"), Description("是否显示页码跳转区域")]
        public bool DisplayGoPage
        {
            get
            {
                return displayGoPage;
            }
            set
            {
                this.displayGoPage = value;
                ViewState["PageControlState_" + this.ID + "_DisplayGoPage"] = value;
            }
        }
        /// <summary>
        /// 是否显示页码跳转区域按钮
        /// </summary>
        [Bindable(true), Category("外观"), Description("是否显示页码跳转区域按钮")]
        public bool DisplayGoPageButton
        {
            get
            {
                return displayGoPageButton;
            }
            set
            {
                this.displayGoPageButton = value;
                ViewState["PageControlState_" + this.ID + "_DisplayGoPageButton"] = value;
            }
        }

        /// <summary>
        /// 用于标识页索引URL查许字符串的参数名
        /// </summary>
        [Bindable(true), Category("数据"), Description("用于标识页索引URL查询字符串的参数名,如CPageQueryName=\"page\",那么会在URL添加如下查询参数page=页码,用于标识页码。")]
        public string CPageQueryName
        {
            get
            {
                return string.IsNullOrEmpty(this.cpagequeryname) ? "page" : this.cpagequeryname;
            }
            set
            {
                cpagequeryname = value;
                ViewState["PageControlState_" + this.ID + "_CPageQueryName"] = value;
            }
        }
        /// <summary>
        /// 每次要显示的页码数
        /// </summary>
        [Bindable(true), Category("数据"), Description("每次要显示的页码数")]
        public int DisplayPage
        {
            get
            {
                return this.Displaypage == 0 ? 10 : this.Displaypage;
            }
            set
            {
                this.Displaypage = value;
                ViewState["PageControlState_" + this.ID + "_Displaypage"] = value;
            }
        }
        /// <summary>
        /// 当前页码的CSS类名
        /// </summary>
        [Bindable(true), Description("当前页码的CSS类名"), Category("外观")]
        public string CurrentPageClassName
        {
            get
            {
                return this.currentPageClassName;
            }
            set
            {
                this.currentPageClassName = value;
                ViewState["PageControlState_" + this.ID + "_CurrentPageClassName"] = value;
            }
        }

        /// <summary>
        /// 页码的CSS类名
        /// </summary>
        [Bindable(true), Description("页码的CSS类名"), Category("外观")]
        public string PageNumberClassName
        {
            get
            {
                return this.pageNumberClassName;
            }
            set
            {
                this.pageNumberClassName = value;
                ViewState["PageControlState_" + this.ID + "_PageNumberClassName"] = value;
            }
        }

        /// <summary>
        /// 第一页和最后页按钮的CSS类名
        /// </summary>
        [Bindable(true), Description("第一页和最后页按钮的CSS类名"), Category("外观")]
        public string FirstAndLastClassName
        {
            get
            {
                return this.firstAndLastClassName;
            }
            set
            {
                this.firstAndLastClassName = value;
                ViewState["PageControlState_" + this.ID + "_FirstAndLastClassName"] = value;
            }
        }

        /// <summary>
        /// 更多页按钮的CSS类名
        /// </summary>
        [Bindable(true), Description("更多页按钮的CSS类名"), Category("外观")]
        public string MorePageClassName
        {
            get
            {
                return this.morePageClassName;
            }
            set
            {
                this.morePageClassName = value;
                ViewState["PageControlState_" + this.ID + "_MorePageClassName"] = value;
            }
        }

        /// <summary>
        /// 当第一,最后页导航按钮失效时的样式表类名
        /// </summary>
        [Bindable(true), Description("当第一,最后页导航按钮失效是的样式表类名"), Category("外观")]
        public string NavigationAbateClassName
        {
            get
            {
                return this.navigationabateClassName;
            }
            set
            {
                this.navigationabateClassName = value;
                ViewState["PageControlState_" + this.ID + "_NavigationAbateClassName"] = value;
            }
        }
        /// <summary>
        /// 第一页按钮的图像
        /// </summary>
        [Description("第一页按钮的图像"), Category("显示")]
        public string FirstImage
        {
            get
            {
                return firstImage;
            }
            set
            {
                this.firstImage = value;
                ViewState["PageControlState_" + this.ID + "_FirstImage"] = value;
            }
        }
        /// <summary>
        /// 最后一页按钮的图像
        /// </summary>
        [Description("最后一页按钮的图像"), Category("显示")]
        public string LastImage
        {
            get
            {
                return lastImage;
            }
            set
            {
                this.lastImage = value;
                ViewState["PageControlState_" + this.ID + "_LastImage"] = value;
            }
        }


        /// <summary>
        /// 第一页按钮的显示文本
        /// </summary>
        [Description("第一页按钮的显示文本"), DefaultValue("first"), Category("显示")]
        public string FirstText
        {
            get
            {
                return this.firstText == null || this.firstText == "" ? "first" : this.firstText;
            }
            set
            {
                this.firstText = value;
                ViewState["PageControlState_" + this.ID + "_FirstText"] = value;
            }
        }
        /// <summary>
        /// 最后一页按钮的显示文本
        /// </summary>
        [Description("最后一页按钮的显示文本"), Bindable(true), DefaultValue("last"), Category("显示")]
        public string LastText
        {
            get
            {
                return this.lastText == null || this.lastText == "" ? "last" : this.lastText;
            }
            set
            {
                this.lastText = value;
                ViewState["PageControlState_" + this.ID + "_LastText"] = value;
            }
        }
        /// <summary>
        /// 更多页码按钮的显示文本
        /// </summary>
        [Description("更多页码按钮的显示文本"), DefaultValue("..."), Category("显示")]
        public string MoreText
        {
            get
            {
                return this.moreText == null || this.moreText == "" ? "..." : this.moreText;
            }
            set
            {
                this.moreText = value;
                ViewState["PageControlState_" + this.ID + "_MoreText"] = value;
            }
        }
        /// <summary>
        /// 更多页码按钮的图像
        /// </summary>
        [Description("更多页码按钮的图像"), Category("显示")]
        public string MoreImage
        {
            get
            {
                return this.moreImage;
            }
            set
            {
                this.moreImage = value;
                ViewState["PageControlState_" + this.ID + "_MoreImage"] = value;
            }
        }
        /// <summary>
        /// 页码控件信息的格式化文本
        /// </summary>
        [Description("页码控件信息的格式化文本\n{0}:共有多少条记录;{1}:每页显示的条数;{2}:计算后分几页显示;{3}:当前页是第几页"), Category("外观"), DefaultValue("<span>共有记录：<b>{0}</b>条，每页显示：<b>{1}</b>条，分<b>{2}</b>页显示，当前页：<b>{3}</b></span>")]
        public string PageMessageFormat
        {
            get
            {
                return string.IsNullOrEmpty(this.pageMessageFormat) ? "<span>总记录：<b>{0}</b>条</span>" : this.pageMessageFormat;
            }
            set
            {
                this.pageMessageFormat = value;
                ViewState["PageControlState_" + this.ID + "_PageMessageFormat"] = value;
            }
        }
        /// <summary>
        ///是否显示第一页的导航按钮
        /// </summary>
        [Description("是否显示第一页的导航按钮"), Bindable(true), DefaultValue(true), Category("显示")]
        public bool DisplayFirstPageButton
        {
            get
            {
                return this.displayfirstpagebutton;
            }
            set
            {
                this.displayfirstpagebutton = value;
                ViewState["PageControlState_" + this.ID + "_DisplayFirstPageButton"] = value;
            }
        }
        /// <summary>
        ///是否显示最后一页的导航按钮
        /// </summary>
        [Description("是否显示最后一页的导航按钮"), Bindable(true), DefaultValue(true), Category("显示")]
        public bool DisplayLastPageButton
        {
            get
            {
                return this.displaylastpagebutton;
            }
            set
            {
                this.displaylastpagebutton = value;
                ViewState["PageControlState_" + this.ID + "_DisplayLastPageButton"] = value;
            }
        }
        /// <summary>
        /// 是否显示上一页按钮
        /// </summary>
        [Bindable(true), Category("显示"), Description("是否显示上一页按钮")]
        public bool DisplayPreviousButton
        {
            get
            {
                return this.displaypreviousbutton;
            }
            set
            {
                this.displaypreviousbutton = value;
                ViewState["PageControlState_" + this.ID + "_DisplayPreviousButton"] = value;
            }
        }
        /// <summary>
        /// 是否显示下一页按钮
        /// </summary>
        [Bindable(true), Category("显示"), Description("是否显示下一页按钮")]
        public bool DisplayNextButton
        {
            get
            {
                return this.displaynextbutton;
            }
            set
            {
                this.displaynextbutton = value;
                ViewState["PageControlState_" + this.ID + "_DisplayNextButton"] = value;
            }
        }


        #endregion
    }
}
